package com.bjfu.gmms.servlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.PhaseMapper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/selectSystemServlet")
public class SelectSystemServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        String message = "";  // 用于存放操作结果信息
        boolean success = false;  // 标识操作是否成功
        int result = 0;
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession("development")){
            PhaseMapper phaseMapper = sqlSession.getMapper(PhaseMapper.class);
            if ("openFirstChoice".equals(action)) {
                // 处理开放第一志愿的逻辑
                System.out.println("开放第一志愿");
                result = phaseMapper.updatePeriodByCollegeAndId(4, 3, 1);
            } else if ("openSecondChoice".equals(action)) {
                // 处理开放第二志愿的逻辑
                System.out.println("开放第二志愿");
                result = phaseMapper.updatePeriodByCollegeAndId(4, 3, 2);
            } else if ("openThirdChoice".equals(action)) {
                // 处理开放第三志愿的逻辑
                System.out.println("开放第三志愿");
                result = phaseMapper.updatePeriodByCollegeAndId(4, 3, 3);
            } else if ("openFreeChoice".equals(action)) {
                // 处理开放自由选择的逻辑
                System.out.println("开放自由选择");
                result = phaseMapper.updatePeriodByCollegeAndId(4, 3, 4);
            }
            sqlSession.commit();  // 确保事务被提交
            if (result > 0) {
                success = true;
                message = "发布成功！";
            } else {
                message = "发布失败，未能更新数据库。";
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "发布失败，未能更新数据库。";
        }
        // 返回结果到页面
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("<script type=\"text/javascript\">");
        response.getWriter().write("alert('" + message + "');");
        response.getWriter().write("window.history.back();"); // 回到之前的页面
        response.getWriter().write("</script>");
    }
}